package freejim.icu.highschoolhealthstatuspost.service;

import freejim.icu.highschoolhealthstatuspost.dao.Info;
import freejim.icu.highschoolhealthstatuspost.dao.InfoRepository;
import freejim.icu.highschoolhealthstatuspost.dao.User;
import freejim.icu.highschoolhealthstatuspost.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService implements UserDetailsService {
    @Resource
    UserRepository userRepository;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    InfoRepository infoRepository;

    public User insert(User user) {
        //存在数据库中的密码应该为密文
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }//测试通过

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = userRepository.findByName(name);
        System.out.println("认证中...");
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole()));
        if (user == null){
            System.out.println("nobody");
            return null;
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }

    public List<Map<String,Object>> getUserList(){
        List<Map<String,Object>> results = new ArrayList<>();
        List<User> userList = userRepository.getAllUser();
        for (User user : userList){
            Map<String,Object> tempResultData = new HashMap<>();
            Info tempUserInfo = infoRepository.getById(user.getId());
            tempResultData.put("username",user.getName());
            tempResultData.put("name",tempUserInfo.getName());
            tempResultData.put("phonenumber",tempUserInfo.getPhonenumber());
            tempResultData.put("role",user.getRole());
            results.add(tempResultData);
        }
        return results;
    }

    public void lockUser(HttpServletRequest request){
        String username = request.getParameter("username");
        userRepository.lockUser(username);
    }

    public void unLockUser(HttpServletRequest request){
        String username = request.getParameter("username");
        userRepository.unLockUser(username);
    }
}
